<article id="wikiArticle">
<div></div>
<p><strong>条件（三元）运算符</strong>是 JavaScript 仅有的使用三个操作数的运算符。本运算符经常作为<code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if</a></code>语句的简短形式来使用。</p>
<div><iframe class="interactive interactive-js" frameborder="0" height="250" src="https://interactive-examples.mdn.mozilla.net/pages/js/expressions-conditionaloperators.html" width="100%"></iframe></div>
<p class="hidden">The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a class="external" href="https://github.com/mdn/interactive-examples" rel="noopener">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p>
<h2 id="语法">语法</h2>
<pre><code class="language-javascript"><em>condition</em> ? <em>expr1</em> : <em>expr2</em> </code></pre>
<h3 id="参数">参数</h3>
<dl>
<dt><code>condition (or conditions)</code></dt>
<dd>计算结果为<code>true</code>或<code>false</code>的表达式。</dd>
</dl>
<dl>
<dt><code>expr1</code>, <code>expr2</code></dt>
<dd>值可以是任何类型的表达式。</dd>
</dl>
<h2 id="描述">描述</h2>
<p>如果<code>condition</code>为<code>true</code>，运算符就会返回<font face="Consolas, Liberation Mono, Courier, monospace"> <code>expr1</code> 的值；否则，</font> 就会返回 <code>expr2 </code>的值。</p>
<p>一个简单的例子，测试你是否达到了美国法定的饮酒年龄。</p>
<pre><code  class="language-javascript">var age = 26;
var canDrinkAlcohol = (age &gt; 21) ? "True, over 21" : "False, under 21";
console.log(canDrinkAlcohol); // "True, over 21"
</code></pre>
<p>另一个例子，根据<code>isMember</code>变量的值显示不同的信息，可以使用下面的表达式：</p>
<pre><code  class="language-javascript">"The fee is " + (isMember ? "$2.00" : "$10.00")
</code></pre>
<p>同样也可以把三元运算符的值赋值给一个变量:</p>
<pre><code  class="language-javascript">var elvisLives = Math.PI &gt; 4 ? "Yep" : "Nope";</code></pre>
<p>多个三元操作符也是可能的（注：条件运算符是右结合）：</p>
<pre><code  class="language-javascript">var firstCheck = false,
    secondCheck = false,
    access = firstCheck ? "Access denied" : secondCheck ? "Access denied" : "Access granted";
  
console.log( access ); // logs "Access granted"</code></pre>
<p>你也可以像使用多重条件的IF表达式一样使用三元运算符</p>
<pre><code  class="language-javascript">var condition1 = true,
    condition2 = false,
    access = condition1 ? (condition2 ? "true true": "true false") : (condition2 ? "false true" : "false false");

console.log(access); // 输出 "true false"</code></pre>
<p>注: 在这里三元表达式的括号不是必须的，删去后不影响执行顺序。在这里加入它们是为了更好的看出结果是如何得出的。</p>
<p>还可以把三元操作符用在等式的左边：</p>
<pre>var stop = false, age = 16;

age &gt; 18 ? location.assign("continue.html") : stop = true;
stop; // true</code></pre>
<p>你也可以在 <code>expr1</code>、<code>expr2</code>里使用一个或多个的操作（用逗号分隔）:</p>
<pre><code  class="language-javascript">var stop = false, age = 23;

age &gt; 18 ? (
    alert("OK, you can go."),
    location.assign("continue.html")
) : (
    stop = true,
    alert("Sorry, you are much too young!")
);
</code></pre>
<p>同样也可以在赋值过程中做多个操作。 如下所示，会将<strong>括号里的最后一个逗号分隔的值</strong>赋给变量<code>url</code>。</p>
<pre><code  class="language-javascript">var age = 16;

var url = age &gt; 18 ? (
    alert("OK, you can go."), 
    // alert 返回的值是 "undefined"， 但它会被忽略，因为
    // 不是括号的最后一个逗号分隔值
    "continue.html" // 如果 age &gt; 18，则这个值赋值给 url
) : (
    alert("You are much too young!"),
    alert("Sorry :-("),
    // 等等
    "stop.html" // 如果 !(age &gt; 18) 为真，则这个值赋值给 url
);

location.assign(url); // "stop.html"</code></pre>
<h3 id="返回三元语句">返回三元语句</h3>
<p>三元运算符能够很好地用在函数返回值的表达式中，此时不需要 <code>if/else</code> 语句。</p>
<pre><code  class="language-javascript">var func1 = function( .. ) {
  if (condition1) { return value1 }
  else { return value2 }
}

var func2 = function( .. ) {
  return condition1 ? value1 : value2
}</code></pre>
<p>一种使用三元表达式作为返回值，测试是否达到美国法定饮酒年龄函数的常用方法</p>
<pre><code  class="language-javascript">function canDrinkAlcohol(age) {
  return (age &gt; 21) ? "True, over 21" : "False, under 21";
}
var output = canDrinkAlcohol(26);
console.log(output); // "True, over 21"</code></pre>
<p>一个发现能恰当替换掉 <code>if/else</code> 表达式的好办法是，观察是否存在 <code>return</code> 关键字被使用多次， 并且每次使用都是在 if 块的内部。</p>
<p>通过将三元表达式使用额外的空格，拆分写在多行，使得三元运算符能干净利落地替代一个很长的<code>if/else</code> 表达式。在语法上，它使用了一种更明快的方式来表达了相同的逻辑:</p>
<pre><code  class="language-javascript">var func1 = function( .. ) {
  if (condition1) { return value1 }
  else if (condition2) { return value2 }
  else if (condition3) { return value3 }
  else { return value4 }
}

var func2 = function( .. ) {
  return condition1 ? value1
       : condition2 ? value2
       : condition3 ? value3
       :              value4
}</code></pre>
<p> </p>
<h2 id="规范">规范</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td><a class="external" href="https://tc39.github.io/ecma262/#sec-conditional-operator" hreflang="en" lang="en" rel="noopener">ECMAScript Latest Draft (ECMA-262)<br/><small lang="zh-CN">Conditional Operator</small></a></td>
<td><span class="spec-Draft">Draft</span></td>
<td> </td>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/ecma-262/6.0/#sec-conditional-operator" hreflang="en" lang="en" rel="noopener">ECMAScript 2015 (6th Edition, ECMA-262)<br/><small lang="zh-CN">Conditional Operator</small></a></td>
<td><span class="spec-Standard">Standard</span></td>
<td> </td>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/ecma-262/5.1/#sec-11.12" hreflang="en" lang="en" rel="noopener">ECMAScript 5.1 (ECMA-262)<br/><small lang="zh-CN">The conditional operator</small></a></td>
<td><span class="spec-Standard">Standard</span></td>
<td> </td>
</tr>
<tr>
<td><a class="external" href="https://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf#sec-11.12" hreflang="en" lang="en" rel="noopener">ECMAScript 1st Edition (ECMA-262)<br/><small lang="zh-CN">The conditional operator</small></a></td>
<td><span class="spec-Standard">Standard</span></td>
<td>首次定义。在 JavaScript 1.0中实现。</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<div class="hidden">The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a class="external" href="https://github.com/mdn/browser-compat-data" rel="noopener">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</div>
<p></p><div class="bc-data"><a class="bc-github-link external" href="https://github.com/mdn/browser-compat-data" rel="noopener">Update compatibility data on GitHub</a><table class="bc-table bc-table-js"><thead><tr class="bc-platforms"><td></td><th class="bc-platform-desktop" colspan="6"><span>Desktop</span></th><th class="bc-platform-mobile" colspan="7"><span>Mobile</span></th><th class="bc-platform-server" colspan="1"><span>Server</span></th></tr><tr class="bc-browsers"><td></td><th class="bc-browser-chrome"><span class="bc-head-txt-label bc-head-icon-chrome">Chrome</span></th><th class="bc-browser-edge"><span class="bc-head-txt-label bc-head-icon-edge">Edge</span></th><th class="bc-browser-firefox"><span class="bc-head-txt-label bc-head-icon-firefox">Firefox</span></th><th class="bc-browser-ie"><span class="bc-head-txt-label bc-head-icon-ie">Internet Explorer</span></th><th class="bc-browser-opera"><span class="bc-head-txt-label bc-head-icon-opera">Opera</span></th><th class="bc-browser-safari"><span class="bc-head-txt-label bc-head-icon-safari">Safari</span></th><th class="bc-browser-webview_android"><span class="bc-head-txt-label bc-head-icon-webview_android">Android webview</span></th><th class="bc-browser-chrome_android"><span class="bc-head-txt-label bc-head-icon-chrome_android">Chrome for Android</span></th><th class="bc-browser-edge_mobile"><span class="bc-head-txt-label bc-head-icon-edge_mobile">Edge Mobile</span></th><th class="bc-browser-firefox_android"><span class="bc-head-txt-label bc-head-icon-firefox_android">Firefox for Android</span></th><th class="bc-browser-opera_android"><span class="bc-head-txt-label bc-head-icon-opera_android">Opera for Android</span></th><th class="bc-browser-safari_ios"><span class="bc-head-txt-label bc-head-icon-safari_ios">Safari on iOS</span></th><th class="bc-browser-samsunginternet_android"><span class="bc-head-txt-label bc-head-icon-samsunginternet_android">Samsung Internet</span></th><th class="bc-browser-nodejs"><span class="bc-head-txt-label bc-head-icon-nodejs">Node.js</span></th></tr></thead><tbody><tr><th scope="row">Conditional operator (<code>c ? t : f</code>)</th><td class="bc-supports-yes bc-browser-chrome"><span class="bc-browser-name">Chrome</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-edge"><span class="bc-browser-name">Edge</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-firefox"><span class="bc-browser-name">Firefox</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              1</td><td class="bc-supports-yes bc-browser-ie"><span class="bc-browser-name">IE</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-opera"><span class="bc-browser-name">Opera</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-safari"><span class="bc-browser-name">Safari</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-webview_android"><span class="bc-browser-name">WebView Android</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-chrome_android"><span class="bc-browser-name">Chrome Android</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-edge_mobile"><span class="bc-browser-name">Edge Mobile</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-firefox_android"><span class="bc-browser-name">Firefox Android</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              4</td><td class="bc-supports-yes bc-browser-opera_android"><span class="bc-browser-name">Opera Android</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-safari_ios"><span class="bc-browser-name">Safari iOS</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-samsunginternet_android"><span class="bc-browser-name">Samsung Internet Android</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td><td class="bc-supports-yes bc-browser-nodejs"><span class="bc-browser-name">nodejs</span><abbr class="bc-level-yes only-icon" title="Full support">
<span>Full support</span>
</abbr>
              Yes</td></tr></tbody></table><section class="bc-legend" id="sect1"><h3 class="offscreen" id="Legend">Legend</h3><dl><dt><span class="bc-supports-yes bc-supports">
<abbr class="bc-level bc-level-yes only-icon" title="Full support">
<span>Full support</span>
                  
                </abbr></span></dt><dd>Full support</dd></dl></section></div><p></p>
<h2 id="参见">参见</h2>
<ul>
<li><a href="Reference/Statements/if...else">if 语句</a></li>
</ul>
</article>